package org.yinxue.example.netty.server.handler;

import java.util.Date;

import org.yinxue.example.netty.core.model.HeartBeatRequest;
import org.yinxue.example.netty.server.util.ChannelHolder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * HeartBeatServerHandler {@link org.yinxue.example.netty.core.codec}
 *
 * @author zengjian
 * @date 2019/1/1
 * @since 1.0.0
 */
public class HeartBeatServerHandler extends SimpleChannelInboundHandler<HeartBeatRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HeartBeatRequest msg) throws Exception {
        System.out.println("服务端接收到请求信息：" + msg);
        // 构建返回消息
        String resp = "服务端已经接收到你的消息,以下是返回消息：" + new Date();
        HeartBeatRequest request = new HeartBeatRequest();
        request.setOptType(-1);
        request.setClientId(-1);
        request.setContentLength(resp.getBytes("utf-8").length);
        request.setContent(resp);
        ctx.writeAndFlush(request);
        ChannelHolder.addChannel(msg.getClientId(), ctx.channel());
    }
}